package com.ymxx.jweb.action.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ymxx.jweb.component.Msg;
import com.ymxx.jweb.persistence.organization.User;
import com.ymxx.jweb.service.security.AccountService;

@Controller
@RequestMapping("/account") 
public class UserAccessAction{

	@Autowired
	private AccountService accountService;

	@RequestMapping(method=RequestMethod.GET)
	public String getCreateForm(Model model) {
		
		model.addAttribute(new User());
		return "account/toRegister"; 
	}
	/**
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(method=RequestMethod.POST,value="register")
	public @ResponseBody void doRegister(HttpServletRequest request,
				HttpServletResponse response)
			throws Exception{
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		User user = new User(name,password);
		try{
			accountService.register(user); 
			response.getWriter().write(new Msg(true, "用户创建成功").toJson());
		}catch(Exception e){
			e.printStackTrace();
			response.getWriter().write(new Msg(false,e.getMessage()).toJson());
		}
		return;
	}
}
